﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OL.FrameCore.Application.Article;
using OL.FrameCore.Application.Home;
using OL.FrameCore.Application.Module;
using OL.FrameCore.Application.Module.Dto;
using OL.FrameCore.Application.User;
using OL.FrameCore.Application.User.Dto;
using OL.FrameCore.Domain.Enum;
using OL.FrameCore.Infrastructure.Security;
using OL.FrameCore.Infrastructure.Utility;
using OL.FrameCore.WebUI.Models;
using OL.FrameCore.WebUI.ViewModels;

namespace OL.FrameCore.WebUI.Controllers
{
    public class HomeController : ControllerBase
    {
        IHomeService _homeService;
        IUserService _userService;
        IModuleService _moduleService;
        IArticleService _articleService;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public HomeController(IHomeService homeService, IUserService userService, IModuleService moduleService, IArticleService articleService, IHttpContextAccessor httpContextAccessor)
        {
            _homeService = homeService;
            _userService = userService;
            _moduleService = moduleService;
            _articleService = articleService;
            _httpContextAccessor = httpContextAccessor;
        }

        public IActionResult Index()
        {

            if (this.HttpContext.User == null)
            {
                return Redirect("/home/login");
            }
            else
            {
                return Redirect("/home/main");
            }
        }

        public IActionResult Header2()
        {
            return View();
        }

        //登录页
        [AllowAnonymous]
        public IActionResult Login()
        {
            return View();
        }

        //登录
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> PostLogin(LoginRequest request)
        {
            //RSA解密
            request.Password = DecryptRSA(request.Password);

            var loginResult = _userService.VerifyLogin(request);

            string ua =this.HttpContext.Request.Headers["User-Agent"];
            string ip = this._httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

            if (loginResult != null&& loginResult.Code == LoginEnum.Success)
            {
                var userInfo = _userService.GetLoginUserInfo(loginResult.UserId);

                //日志
                _userService.LogLogin(new LogLoginRequest
                {
                    UserName = userInfo.UserName,
                    UserId = userInfo.UserId,
                    LoginStatus = 1,
                    IP = ip,
                    UserAgent = ua
                });

                //用户标识
                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaim(new Claim(ClaimTypes.Sid, userInfo.UserId.ToString()));
                identity.AddClaim(new Claim(ClaimTypes.Name, userInfo.UserName));
                identity.AddClaim(new Claim("TrueName", userInfo.TrueName));
                identity.AddClaim(new Claim(ClaimTypes.Role, userInfo.Role));
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity),
                    new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc = DateTimeOffset.Now.Add(new TimeSpan(10, 0, 0))
                    });

                return SuccessResult();
            }
            else
            {
                //日志
                _userService.LogLogin(new LogLoginRequest
                {
                    UserName = request.UserName,
                    UserId = loginResult.UserId,
                    LoginStatus = 2,
                    IP = ip,
                    UserAgent = ua
                });

                switch (loginResult.Code)
                {
                    case LoginEnum.UserDisable:
                        return FailResult("当前登录用户被禁用");
                    case LoginEnum.NoUser:
                        return FailResult("没有该用户");
                    case LoginEnum.WrongPassword:
                        return FailResult("用户名或密码错误");
                    default:
                        return FailResult("登录异常");
                }
                
            }
        }

        /// <summary>
        /// 验证码
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public IActionResult GetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(4);
            //HttpContext.Session.SetString("ValidateCode", code);
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");

            //string code = "";
            ////HttpContext.Session.SetString("ValidateCode", code);
            //byte[] bytes = ValidateCode.CreateVerifyCode2(out code);
            //return File(bytes, @"image/jpeg");
        }

        //登出
        [AllowAnonymous]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Login", "Home");
        }

        //框架页
        public IActionResult Main()
        {
            return View();
        }

        //头部
        public IActionResult Header()
        {
            return View();
        }

        //左边菜单
        public IActionResult Left()
        {
            return View();
        }

        public IActionResult Menu()
        {
            //var serviceResult = _moduleService.GetAllModuleList();
            var serviceResult = _userService.GetUserMenu(UserId);
            var result = CreateModuleTreeNode(serviceResult);
            return Json(result);
        }
        private List<MenuNodeView> CreateModuleTreeNode(IList<GetModuleListModel> list, int parentId = 0)
        {
            List<MenuNodeView> result = new List<MenuNodeView>();

            var listTmp = list.Where(p => p.ParentId == parentId).OrderBy(p=>p.SortIndex).ToList();
            foreach (var li in listTmp)
            {
                MenuNodeView model = new MenuNodeView
                {
                    Id = li.Id,
                    Title = li.ModuleName,
                    Url = li.MenuPath,
                    Icon = li.Icon,
                    ChildNodes = CreateModuleTreeNode(list, li.Id)
                };
                result.Add(model);
            }

            return result;
        }

        public IActionResult Overview()
        {
            return View();
        }

        /// <summary>
        /// 获当前数据
        /// </summary>
        /// <returns></returns>
        public IActionResult GetCurrentData()
        {
            var data = _homeService.GetCurrentData();
            return Json(data);
        }
        /// <summary>
        /// 获取登录数据
        /// </summary>
        /// <returns></returns>
        public IActionResult GetLoginStatistics()
        {
            var data = _homeService.GetLoginStatistics();
            var resul = new
            {
                DataList = data.Select(p => p.Date).ToList(),
                ValueList = data.Select(p => p.LoginNum).ToList()
            };
            return Json(resul);
        }
        /// <summary>
        /// 获取用户分布数据
        /// </summary>
        /// <returns></returns>
        public IActionResult GetUserDistribution()
        {
            var data = _homeService.GetUserDistribution();
            return Json(data);
        }
        /// <summary>
        /// 获文章列表
        /// </summary>
        /// <returns></returns>
        public IActionResult GetArticleList(int type = 1,int num=8)
        {
            var serviceResult = _articleService.GetArticleViewList(type, num);
            return Json(serviceResult);
        }
        /// <summary>
        /// 获取我的登录数据数据
        /// </summary>
        /// <returns></returns>
        public IActionResult GetMyLoginData()
        {
            var data = _homeService.GetMyLoginData(this.UserId);
            data.UserName = this.UserName;
            return Json(data);
        }
    }
}
